package edu.fudan.jwxt.service.Impl;

import cn.hutool.core.util.ReUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.fudan.jwxt.Exception.ServiceException;
import edu.fudan.jwxt.common.Constants;
import edu.fudan.jwxt.dao.ClassroomDao;
import edu.fudan.jwxt.dao.CourseDao;
import edu.fudan.jwxt.entity.Classroom;
import edu.fudan.jwxt.service.ClassroomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;

@Service
public class ClassroomServiceImpl extends ServiceImpl<ClassroomDao, Classroom> implements ClassroomService {

    @Autowired
    private CourseDao courseDao;

    @Autowired
    private ClassroomDao classroomDao;

    @Override
    public boolean save(Classroom entity) {
        if(!nameCheck(entity.getName()))
            throw new ServiceException(Constants.CODE_600,"教室名称格式不正确");

        LambdaQueryWrapper<Classroom> q = new LambdaQueryWrapper<>();
        q.eq(Classroom::getName,entity.getName());
        Classroom one = getOne(q);
        if(one != null)
            throw new ServiceException(Constants.CODE_600,"教室已存在");

        return super.save(entity);
    }

    @Override
    public boolean updateById(Classroom entity) {
        if(!nameCheck(entity.getName()))
            throw new ServiceException(Constants.CODE_600,"教室名称格式不正确");

        return super.updateById(entity);
    }

    @Override
    public Classroom getById(Serializable id){
        Classroom classroom = classroomDao.selectById(id);
        if(classroom == null)
            throw new ServiceException(Constants.CODE_600,"教室不存在");
        return classroom;
    }

    @Override
    public String getNameById(Serializable id){
        Classroom classroom=getById(id);
        return classroom.getName();
    }

    /*
    @Override
    public boolean removeById(Serializable id) {
        LambdaQueryWrapper<Course> q1 = new LambdaQueryWrapper<>();
        q1.eq(Course::getCoursePlace,getById(id).getName());
        long courseCount = courseDao.selectCount(q1);

        if(courseCount != 0)
            throw new ServiceException(Constants.CODE_600,"该教室已被安排课程");

        return super.removeById(id);
    }
    */


    private boolean nameCheck(String name){
        String r = "^[A-Z]{1,3}\\d{3,4}";

        return ReUtil.isMatch(r,name);
    }


}
